package com.unittec.drainage.provider.auth.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unittec.drainage.provider.auth.entity.SysAppVersion;
import com.unittec.drainage.provider.auth.service.SysAppVersionService;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.utils.CopyListUtils;
import com.unittec.drainage.provider.utils.OssUtils;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.domain.SysAppVersionRes;
import com.unittec.drainage.sdk.auth.request.*;
import com.unittec.drainage.sdk.auth.response.*;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;
import com.unittec.drainage.sdk.root.enums.BizCodeEnum;
import com.unittec.drainage.sdk.root.internal.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wyf
 * @description 应用Controller
 * @date 2021/4/23
 */
@RestController
@Api(tags = "app版本管理")
public class SysAppVersionController {

    @Resource
    Log log;

    @Resource
    private SysAppVersionService sysAppVersionService;

    @RequestMapping(value = "/101520", method = RequestMethod.POST)
    @ApiOperation(value = "app版本分页列表", notes = "app版本分页列表")
    @ResponseBody
    public Result<Res101520> pageVersion(@RequestBody GatewayRequest<Req101520> req){
        log.debug(req, "pageVersion {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101520 res101520 = null;
        try {
            Page<SysAppVersion> pageList = sysAppVersionService.selectPageVersion(req.getContent());
            res101520 = new Res101520();
            res101520.setPage(pageList);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "pageVersion {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            return Result.success(req, res101520);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }


    @RequestMapping(value = "/101521", method = RequestMethod.POST)
    @ApiOperation(value = "新增app版本", notes = "新增app版本")
    @ResponseBody
    public Result<Res101521> addVersion(@RequestBody GatewayRequest<Req101521> req) {
        log.debug(req, "addAppVersion {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101521 res101521 = null;
        try {
            //校验数据
            ValidationUtils.validateEntityStr(req.getContent());


            //从请求中取数据
            SysAppVersion sysAppVersion = new SysAppVersion();
            BeanUtils.copyProperties(req.getContent(), sysAppVersion);

            //自定义校验
            //--排序versionCode不能重复
            if (sysAppVersionService.judgeVersionCode(sysAppVersion.getVersionCode(),sysAppVersion.getModel())) {
                throw new BusinessException("该版本号已经存在，请重新输入");
            }

            //后端赋数据
            //1->版本名，为大中小版本号的拼接
            String versionName = new StringBuilder()
                    .append("v")
                    .append(sysAppVersion.getVersionMajor())
                    .append(".").append(sysAppVersion.getVersionMedium())
                    .append(".").append(sysAppVersion.getVersionMinor()).toString();

            //--版本名不能重复
            if (sysAppVersionService.judgeVersionName(versionName,sysAppVersion.getModel())) {
                throw new BusinessException("该版本名已经存在，请重新输入");
            }
            //保存
            sysAppVersion.setVersionName(versionName);
            sysAppVersionService.save(sysAppVersion);
            //设置成功的Response
            res101521 = new Res101521();
            res101521.setIsSuccess(true);
            res101521.setId(sysAppVersion.getId());
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101521", JSON.toJSONString(req), "新增app版本", log.buildErrmsg(e),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        } finally {
            log.debug(req, "addAppVersion {}  ", "end");
        }
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101521", JSON.toJSONString(req), "新增app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101521);
        } else {
            log.addOperateLog("101521", JSON.toJSONString(req), "新增app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }


    @RequestMapping(value = "/101522", method = RequestMethod.POST)
    @ApiOperation(value = "修改app版本信息", notes = "修改app版本信息")
    @ResponseBody
    public Result<Res101522> updateVersion(@RequestBody GatewayRequest<Req101522> req) {
        log.debug(req, "updateVersion {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101522 res101522 = null;
        try {
            //验证各字段是否为空
            ValidationUtils.validateEntityStr(req.getContent());
            //自定义验证字段
            //--versionCode除了自己，表中是否还存在
            if (sysAppVersionService.judgeVersionCodeExceptThis(
                    req.getContent().getVersionCode(),
                    req.getContent().getId(),
                    req.getContent().getModel())) {
                throw new BusinessException("该版本号已经存在，请重新输入");
            }


            //从请求中取数据
            SysAppVersion sysAppVersion = new SysAppVersion();
            BeanUtils.copyProperties(req.getContent(), sysAppVersion);

            //--versionName除了自己，表中是否还存在
            String versionName = new StringBuilder()
                    .append("v")
                    .append(sysAppVersion.getVersionMajor()).append(".")
                    .append(sysAppVersion.getVersionMedium()).append(".")
                    .append(sysAppVersion.getVersionMinor()).toString();
            if (sysAppVersionService.judgeVersionNameExceptThis(versionName, sysAppVersion.getId(),sysAppVersion.getModel())) {
                throw new BusinessException("该版本名已经存在，请重新输入");
            }
            //给versionName赋值
            sysAppVersion.setVersionName(versionName);
            //通过id更新数据
            sysAppVersionService.updateById(sysAppVersion);
            //设置成功的Response
            res101522 = new Res101522();
            res101522.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101522", JSON.toJSONString(req), "修改app版本信息", log.buildErrmsg(e),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        //操作结束
        log.debug(req, "updateVersion {}  ", "end");
        //判断是否成功
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101522", JSON.toJSONString(req), "修改app版本信息", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101522);
        } else {
            log.addOperateLog("101522", JSON.toJSONString(req), "修改app版本信息", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }


    @RequestMapping(value = "/101523", method = RequestMethod.POST)
    @ApiOperation(value = "删除app版本", notes = "删除app版本")
    @ResponseBody
    public Result<Res101523> deleteVersion(@RequestBody GatewayRequest<Req101523> req) {
        log.debug(req, "deleteVersion {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101523 res101523 = null;
        try {
            //验证各字段是否为空
            ValidationUtils.validateEntityStr(req.getContent());

            //判断数据库中是否还存在该id
            String id = req.getContent().getId();
            if (null == sysAppVersionService.getById(id)) {
                throw new BusinessException("该版本号不存在，请重新输入");
            }
            sysAppVersionService.removeById(id);
            //设置成功的Response
            res101523 = new Res101523();
            res101523.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101523", JSON.toJSONString(req), "删除app版本", log.buildErrmsg(e),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        //操作结束
        log.debug(req, "updateVersion {}  ", "end");
        //判断是否成功
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101523", JSON.toJSONString(req), "删除app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101523);
        } else {
            log.addOperateLog("101523", JSON.toJSONString(req), "删除app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }


    @RequestMapping(value = "/101524", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有app版本", notes = "查询所有app版本")
    @ResponseBody
    public Result<Res101524> findAllVersion(@RequestBody GatewayRequest<Req101524> req) {
        log.debug(req, "findAllVersion {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101524 res101524 = null;
        try {
            List<SysAppVersion> list = sysAppVersionService.list();
            if (list.size() < 1) {
                throw new BusinessException("没有数据，请先添加数据");
            }
            //设置成功的Response
            res101524 = new Res101524();
            res101524.setList(CopyListUtils.copyList(list, SysAppVersionRes.class));
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101524", JSON.toJSONString(req), "查询所有app版本", log.buildErrmsg(e),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        //操作结束
        log.debug(req, "findAllVersion {}  ", "end");
        //判断是否成功
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101524", JSON.toJSONString(req), "查询所有app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101524);
        } else {
            log.addOperateLog("101524", JSON.toJSONString(req), "查询所有app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }


    @RequestMapping(value = "/101525", method = RequestMethod.POST)
    @ApiOperation(value = "根据机型获取最新app版本", notes = "根据机型获取最新app版本")
    @ResponseBody
    public Result<Res101525> getLatesVersion(@RequestBody GatewayRequest<Req101525> req) {
        log.debug(req, "getLatesVersion {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101525 res101525 = null;
        try {
            //验证各字段是否为空
            String model = req.getContent().getModel();
            res101525 = new Res101525();

            List<SysAppVersionRes> list = new ArrayList<>();
            //判断是前端请求的还是app端请求的
            if (StringUtils.isBlank(model)) {
                //需要请求的所有版本
                String[] modelList = {"1","2"};
                for (String c : modelList) {
                    SysAppVersion latestByModel = sysAppVersionService.getLatestByModel(c);
                    if(latestByModel==null) {
                        continue;
                    }
                    SysAppVersionRes resSysAppVersion = new SysAppVersionRes();
                    //机型
                    resSysAppVersion.setModel(latestByModel.getModel());
                    //版本名
                    resSysAppVersion.setVersionName(latestByModel.getVersionName());
                    //下载地址img_url优先
                    String url = StringUtils.isNotBlank(latestByModel.getImgUrl()) ? latestByModel.getImgUrl() : latestByModel.getAppUrl();
                    resSysAppVersion.setAppUrl(OssUtils.getUrl(url,1));
                    list.add(resSysAppVersion);
                }
                //将list放入响应体中
                res101525.setList(list);
            }else{
                SysAppVersion latestByModel = sysAppVersionService.getLatestByModel(model);
                if(latestByModel!=null){
                    SysAppVersionRes sysAppVersionRes = new SysAppVersionRes();
                    //机型
                    sysAppVersionRes.setModel(latestByModel.getModel());
                    //版本名
                    sysAppVersionRes.setVersionName(latestByModel.getVersionName());
                    //下载地址img_url优先
                    String url = StringUtils.isNotBlank(latestByModel.getImgUrl()) ? latestByModel.getImgUrl() : latestByModel.getAppUrl();

                    sysAppVersionRes.setAppUrl(OssUtils.getUrl(url,1));
                    //升级说明
                    sysAppVersionRes.setVersionDescribe(latestByModel.getVersionDescribe());
                    //升级策略
                    sysAppVersionRes.setStrategy(latestByModel.getStrategy());
                    //版本号
                    sysAppVersionRes.setVersionCode(latestByModel.getVersionCode());
                    list.add(sysAppVersionRes);
                }
                //将list放入响应体中
                res101525.setList(list);
            }
            bizCodeEnum = BizCode.SUCCESS;

        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101525", JSON.toJSONString(req), "根据机型获取最新app版本", log.buildErrmsg(e),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        //操作结束
        log.debug(req, "getLatesVersion {}  ", "end");
        //判断是否成功
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101524", JSON.toJSONString(req), "根据机型获取最新app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101525);
        } else {
            log.addOperateLog("101525", JSON.toJSONString(req), "根据机型获取最新app版本", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }


}

